﻿using Max.Ph5_2009A.NewShopping.DTO;
using Max.Ph5_2009A.NewShopping.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Max.Ph5_2009A.NewShopping.API.Controllers.Member
{
    /// <summary>
    /// 会员订单控制器
    /// </summary>
    [Route("member/order")]
    [ApiController]
    public class MemberOrderController : ControllerBase
    {
        IOrderMasterInfoService _orderService;
        IOrderDetailInfoService _orderDetailService;
        IProductSKUService _productSKUSService;
        IProductSKUImageService _productSKUImageService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="orderService"></param>
        public MemberOrderController(IOrderMasterInfoService orderService, IOrderDetailInfoService orderDetailService,
            IProductSKUService productSKUSService, IProductSKUImageService productSKUImageService)
        {
            _orderService = orderService;
            _orderDetailService = orderDetailService;
            _productSKUSService = productSKUSService;
            _productSKUImageService = productSKUImageService;
        }


        /// <summary>
        /// 订单查询
        /// </summary>
        /// <param name="memberId"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetOrderData(string memberId, string type = "-1", int pageSize = 10, int pageIndex = 1)
        {
            ResponseResultOutputDto dto = new();

            if (string.IsNullOrEmpty(memberId))
            {
                dto.Code = Domain.Shared.ResponseResultStateCode.系统错误;
                dto.Message = "参数无效";
                return BadRequest(dto);
            }

            if (pageSize <= 0) pageSize = 10;
            if (pageIndex <= 0) pageIndex = 1;

            //查询所有数据(是你的所有订单数据)
            var list = _orderService.Select().Where(x => memberId.Equals(x.MemberId.ToString()));

            //根据下单时间来决定，这个订单是今天的，还是昨天的
            switch (type)
            {
                //全部
                case "-1":
                    break;
                //今天
                case "1":
                    list = list.Where(x => x.OrderTime.Date == System.DateTime.Now.Date);
                    break;
                //昨天 
                case "2":
                    list = list.Where(x => x.OrderTime.Date == System.DateTime.Now.Date.AddDays(-1));
                    break;
                //本周 
                case "3":
                    var w = System.DateTime.Now.DayOfWeek; //得到当前星期几（枚举）
                    var before = System.DateTime.Now.AddDays(-(int)w);  //得到这个星期中，距今天的前几天
                    var begin = System.DateTime.Now.AddDays((7 - 1) - (int)w); //得到这个星期中，距今天的后几天
                    Console.WriteLine("====================================");
                    Console.WriteLine(before.Date);
                    Console.WriteLine(begin.Date);
                    Console.WriteLine("====================================");
                    list = list.Where(x => x.OrderTime.Date >= before.Date && x.OrderTime.Date <= begin.Date);
                    break;
                //本月
                case "4":
                    var m = System.DateTime.Now.Month;
                    list = list.Where(x => x.OrderTime.Month == m);
                    break;
            }


            //订单总数
            var count = list.Count();
            //订单总金额
            //decimal total2 = 0;
            //list.ToList().ForEach(x =>
            //{
            //    total2 += x.Total;
            //});
            var amount = list.Sum(x => x.Total);

            //分页
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            //var q = from a in list
            //        select new
            //        {
            //            a.Id,
            //            a.OrderNo,
            //            a.MemberId,
            //            a.OrderState,
            //            a.PayMoney,
            //            a.OrderTime,
            //            payStateValue = a.PayType.ToString()
            //        };

            dto.Data = new
            {
                items = list, //分页的数据
                total = count, //总条数
                count = count, //订单总记录数
                amount = amount  //订单总金额
            };

            return Ok(dto);
        }

        /// <summary>
        /// 获取订单状态-枚举下拉
        /// </summary>
        /// <returns></returns>
        [HttpGet("state")]
        public IActionResult GetOrderState()
        {
            ResponseResultOutputDto dto = new();

            List<dynamic> list = new();

            //获取枚举类型
            var t = typeof(Domain.Shared.OrderState);

            //获取枚举字段数组
            var fields = t.GetEnumNames();

            fields.ToList().ForEach(x =>
            {
                int value = (int)Enum.Parse(t, x);
                string key = "";
                //获取这个字段和它的自定义的描述特性
                var f = t.GetField(x);
                var objects = f.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), true);
                if (objects != null && objects.Length > 0)
                {
                    //描述特性不为空，则取描述
                    key = ((System.ComponentModel.DataAnnotations.DisplayAttribute)objects[0]).Description ?? x;
                }
                else
                {
                    key = x;
                }
                list.Add(new { key = key, value = value });
            });
            dto.Data = list;

            return Ok(dto);
        }


        /// <summary>
        /// 获取订单详情（详细信息：订单信息和订单的商品信息）
        /// </summary>
        /// <returns></returns>
        [HttpGet("detail")]
        public IActionResult GetOrderDetail(string orderNo)
        {
            ResponseResultOutputDto dto = new();

            if (string.IsNullOrEmpty(orderNo))
            {
                dto.Code = Domain.Shared.ResponseResultStateCode.系统错误;
                dto.Message = "参数无效";
                return BadRequest(dto);
            }

            //订单信息
            var order = _orderService.Select().Where(x => x.OrderNo.Equals(orderNo)).FirstOrDefault();
            //订单商品信息(一个订单有可能有多个商品，最少有一个商品)
            //var detail = _orderDetailService.Select().Where(x => x.OrderNo.Equals(orderNo));

            var detail = from a in _orderDetailService.Select()
                         join b in _productSKUSService.Select() on a.GoodsId equals b.Id
                         where a.OrderNo.Equals(orderNo)
                         select new
                         {
                             b.Id,
                             a.GoodsNumber,
                             a.GoodsPrice,
                             b.Name,
                             imagePath = _productSKUImageService.Select().Where(x => x.ProductSKUId.Equals(b.Id)).FirstOrDefault().ImagePath ?? "images/product/lx1.png"
                         };

            dto.Data = new { order, detail };
            return Ok(dto);
        }

    }
}
